package de.stefanocke.roo.wicket;

import org.springframework.roo.classpath.details.MemberHoldingTypeDetails;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.scanner.MemberDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.apache.commons.lang3.Validate;

public class MoreMemberFindingUtils {

	/**
	 * Locates a method with the given name. Searches all {@link MemberDetails}
	 * until the first such method is located
	 * or none can be found.
	 * 
	 * @param memberDetails
	 *            the {@link MemberDetails} to search (required)
	 * @param methodName
	 *            the method name to locate (required)
	 * @return the first located method, or null if such a method cannot be
	 *         found
	 */
	public static MethodMetadata getMethod(MemberDetails memberDetails, JavaSymbolName methodName) {
		Validate.notNull(memberDetails, "Member details required");
		Validate.notNull(methodName, "Method name required");
		for (MemberHoldingTypeDetails memberHoldingTypeDetails : memberDetails.getDetails()) {
			MethodMetadata md = getDeclaredMethod(memberHoldingTypeDetails, methodName);
			if (md != null) {
				return md;
			}
		}
		return null;
	}

	/**
	 * Locates the specified method.
	 * 
	 * @param memberHoldingTypeDetails
	 *            the {@link MemberHoldingTypeDetails} to search (required)
	 * @param methodName
	 *            to locate (required)
	 * 
	 * @return the method, or null if not found
	 */
	public static MethodMetadata getDeclaredMethod(MemberHoldingTypeDetails memberHoldingTypeDetails,
			JavaSymbolName methodName) {
		Validate.notNull(memberHoldingTypeDetails, "Member holding type details required");
		Validate.notNull(methodName, "Method name required");

		for (MethodMetadata method : memberHoldingTypeDetails.getDeclaredMethods()) {
			if (method.getMethodName().equals(methodName)) {
				return method;
			}
		}
		return null;
	}
	
}
